package com.base.sharding.transaction.aspect;

import com.base.sharding.transaction.annotations.ShardingTransaction;
import org.apache.shardingsphere.transaction.core.TransactionTypeHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author liuyjy
 * @Date 2022/2/25 16:36
 * @Description: 代理
 **/
@Component
@Aspect
@Order(-1)
public class ShardingTransactionAspect {
    private static Logger LOGGER = LoggerFactory.getLogger(ShardingTransactionAspect.class);


    @Pointcut("@within(com.base.sharding.transaction.annotations.ShardingTransaction)||" +
            " @annotation(com.base.sharding.transaction.annotations.ShardingTransaction)")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void doBefore(JoinPoint point) {
        ShardingTransaction ShardingTransaction = point.getTarget().getClass().getAnnotation(ShardingTransaction.class);
        if (ShardingTransaction == null) {
            //注解在类上
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            ShardingTransaction = method.getAnnotation(ShardingTransaction.class);
        }
        TransactionTypeHolder.set(ShardingTransaction.value());
        LOGGER.info("选择Sharding分布式事务---" + ShardingTransaction.value().toString());
    }


    @After("pointCut()")
    public void doAfter() {
        TransactionTypeHolder.clear();
    }
}
